#include <iostream>
#include <boost\tokenizer.hpp>

#include "SQLSystem.h"
#include "CreateCommand.h"
#include "InsertCommand.h"
#include "SelectCommand.h"
#include "UnloadCommand.h"
#include "DropCommand.h"
#include "DeleteCommand.h"
using namespace boost;

SQLSystem::SQLSystem()
{
}


SQLSystem::~SQLSystem()
{
}

vector<Table *> SQLSystem::getAllTables()
{
	return tables;
}

Table* SQLSystem::getTableByName(string name)
{
	Table* table;
	for(unsigned int i=0;i<tables.size();i++)
	{
		if(helper->toUpperString(name) == helper->toUpperString(tables[i]->getName()))
		{
			table= tables[i];
			return table;
		}
	}
	return NULL;
}

int SQLSystem::getTableIndex(string table)
{
	for(unsigned int i=0;i<tables.size();i++)
	{
		if(helper->toUpperString(table) == helper->toUpperString(tables[i]->getName()))
			return i;
	}
	return -1;
}

void SQLSystem::removeTable(string name)
{
	int index= getTableIndex(name);
	if(index == -1)
	{
		cout << "No table found\n";
		return;
	}
	tables.erase(tables.begin()+index);
}

void SQLSystem::addTable(Table* table)
{
	tables.push_back(table);
}

void SQLSystem::input()
{
	getline(cin, statement);
}

void SQLSystem::process()
{
	

}


void SQLSystem::run()
{
	bool stop=false;
	while(!stop)
	{
		cout << "ENTER THE COMMAND: ";
		input();
		typedef tokenizer<char_separator<char>> token;
		char_separator<char> sep(" ","(),",drop_empty_tokens);
		token tok(statement, sep);
		token::iterator tok_iter= tok.begin();
		if(helper->toUpperString(*tok_iter) == "CREATE")
		{
			CreateCommand createComm(this);
			command= &createComm;
			if(!command->execute(statement))
			{
				cout << "ERROR CREATING TABLE\n";
			}
		
		}
		else if(helper->toUpperString(*tok_iter) == "INSERT")
		{
			InsertCommand insertComm(this);
			command= &insertComm;
			if(!command->execute(statement))
			{
				cout << "ERROR INSERTING RECORD\n";
			}
		}
		else if(helper->toUpperString(*tok_iter) == "EXIT")
			return;
		else if(helper->toUpperString(*tok_iter) == "SELECT")
		{
			SelectCommand selectComm(this);
			command= &selectComm;
			if(!command->execute(statement))
			{
				cout << "ERROR SELECTING RECORDS\n";
			}
		}
		else if(helper->toUpperString(*tok_iter) == "UNLOAD")
		{
			UnloadCommand unloadComm(this);
			command= &unloadComm;
			if(!command->execute(statement))
			{
				cout << "ERROR UNLOADING DATA\n";
			}
		}
		else if(helper->toUpperString(*tok_iter) == "DROP")
		{
			DropCommand dropComm(this);
			command= &dropComm;
			if(!command->execute(statement))
			{
				cout << "ERROR DROPPING TABLE\n";
			}
		}
		else if(helper->toUpperString(*tok_iter) == "DELETE")
		{
			DeleteCommand deleteComm(this);
			command= &deleteComm;
			if(!command->execute(statement))
			{
				cout << "ERROR DELETING RECORDS\n";
			}
		}
		else
			cout << "WRONG COMMAND\n";

	}
}

